import store from '../store'

export default class WebSocketService {
  constructor(url) {
    this.socket = new WebSocket(url)
    this.retries = 0
    this.maxRetries = 3

    this.socket.onopen = () => {
      console.log('WebSocket 连接成功')
      this.retries = 0
    }

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data)
      if (data.type === 'REVIEW_UPDATE') {
        store.commit('review/updateStages', data.payload)
      }
    }

    this.socket.onclose = () => {
      if (this.retries < this.maxRetries) {
        setTimeout(() => {
          this.retries++
          this.reconnect()
        }, 2000 * this.retries)
      }
    }
  }

  reconnect() {
    this.socket = new WebSocket(this.url)
  }

  close() {
    this.socket.close()
  }
}